#include "FTMerger.h"
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

FTMerger::FTMerger()
{
}

FTMerger::~FTMerger()
{
}

void FTMerger::merge(ifstream* file0, ifstream* file1, ofstream* destination)
{
	uint word0 =0;
	uint word1 =0;
	bool eof0 = false;
	bool eof1 = false;
	string cont0 = "";
	string cont1 = "";
	
	
	
	if(!file0->is_open() || !file1->is_open())
	{
		cout << "Problems opening files... Try again =(" << endl;
	}
	
	*file0 >> word0;
	*file1 >> word1;
	while(!eof0 || !eof1)
	{
		if(word0 < word1 || eof1 )
		{
			*destination << word0 << " ";
			getline(*file0,cont0);
			*destination << cont0 << endl;
			if(!file0->eof())
				*file0 >> word0;
			else {
				eof0 = true;
				word0 = INT64_MAX; }
		}
		else
		{
			if(word1 < word0 )
			{
				*destination << word1 << " ";
				getline(*file1,cont1);
				*destination << cont1 << endl;
				if(!file1->eof())
					*file1 >> word1;
				else {
					eof1 = true;
					word1 = INT64_MAX; }
			}
			else
			{
				*destination << word0 << " ";
				getline(*file0,cont0);
				cont0 = cont0.substr(0,cont0.size()-2);
				getline(*file1,cont1);
				*destination << cont0 << cont1 << endl;
				if(!file0->eof())
					*file0 >> word0;
				else {
					eof0 = true;
					word0 = INT64_MAX; }
				if(!file1->eof())
					*file1 >> word1;
				else {
					eof1 = true;
					word1 = INT64_MAX; }
			}
		}
	}
}